package com.tloss.stdao.service;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import com.tloss.stdao.JPAResourceBean;
import com.tloss.stdao.StockHistory;

public class StockHistoryService {
	public List<StockHistory> select() {
		EntityManager em = JPAResourceBean.getEMF().createEntityManager();
		Query q = em.createQuery("select t from StockHistory t");
		List<StockHistory> histories = q.getResultList();
		em.close();
		return histories;
	}

	public StockHistory select(int transactionId) {
		EntityManager em = JPAResourceBean.getEMF().createEntityManager();
		StockHistory history = em.find(StockHistory.class, transactionId);
		em.clear();
		return history;
	}

	public List<StockHistory> select(String username) {
		EntityManager em = JPAResourceBean.getEMF().createEntityManager();
		Query q = em
				.createQuery("select t from StockHistory t where t.username=?1 order by t.transactionDate DESC");
		q.setParameter(1, username);
		List<StockHistory> histories = q.getResultList();
		em.close();
		return histories;
	}

	public List<StockHistory> select(String username, String stock) {
		EntityManager em = JPAResourceBean.getEMF().createEntityManager();
		Query q = em
				.createQuery("select t from StockHistory t where t.username=?1 and t.stock =?2");
		q.setParameter(1, username);
		q.setParameter(2, stock);
		List<StockHistory> histories = q.getResultList();
		em.close();
		return histories;
	}
	public void insert(StockHistory history){
		EntityManager em = JPAResourceBean.getEMF().createEntityManager();
		EntityTransaction transaction = em.getTransaction();
		transaction.begin();
		em.persist(history);
		transaction.commit();
		em.close();
	}
}
